#include "fml_key.h"

void apl_key_init(void)
{

}

uint32_t apl_key_scan_task(void)
{
    static uint8_t led_onoff = 0;
    static int32_t pwm_value = 20;
    
    if (led_ctrl_key[KEY_LED_UP].flag)
    {
        if ((HAL_GetTick() - led_ctrl_key[KEY_LED_UP].timestamp) > 10)
        {
            led_ctrl_key[KEY_LED_UP].flag = 0;
            if (fml_key_read() & (1 << KEY_LED_UP))
            {
                if (led_onoff)
                {
                    pwm_value += 5;
                    if (pwm_value > 39)
                        pwm_value = 39;
                    printf("LED+ %d\n", pwm_value);
                    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, pwm_value);
                }
            }
        }
    }
    if (led_ctrl_key[KEY_LED_DOWN].flag)
    {
        if ((HAL_GetTick() - led_ctrl_key[KEY_LED_DOWN].timestamp) > 10)
        {
            led_ctrl_key[KEY_LED_DOWN].flag = 0;
            if (fml_key_read() & (1 << KEY_LED_DOWN))
            {
                if (led_onoff)
                {
                    pwm_value -= 5;
                    if (pwm_value < 0)
                        pwm_value = 0;
                    printf("LED- %d\n", pwm_value);
                    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, pwm_value);
                }
            }
        }
    }    
    if (led_ctrl_key[KEY_LED_ONOFF].flag)
    {
        if ((HAL_GetTick() - led_ctrl_key[KEY_LED_ONOFF].timestamp) > 10)
        {
            led_ctrl_key[KEY_LED_ONOFF].flag = 0;
            if (fml_key_read() & (1 << KEY_LED_ONOFF))
            {
                if (led_onoff)
                {
                    led_onoff = 0;
                    printf("LED OFF\n");
                    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, 0);
                }
                else
                {
                    led_onoff = 1;
                    printf("LED ON\n");
                    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, 20);
                }
            }
        }
    } 
}